package argsRule

import (
	"errors"
	"net/url"
	"sieve_admin_server_userpass/lib/util/convert"
	"strconv"
	"strings"
)

type RuleType byte

const (
	RString RuleType = iota + 1
	RInt
)

type RuleInfo struct {
	Type  RuleType
	Field string
	Msg   string
	Min   int
}

func VerifyArgs(args url.Values, required ...RuleInfo) error {
	for _, v := range required {
		if args == nil {
			return errors.New(v.Msg)
		}
		values, ok := args[v.Field]
		if !ok {
			return errors.New(v.Msg)
		}
		switch v.Type {
		case RInt:
			i, _ := strconv.Atoi(values[0])
			if i < v.Min {
				return errors.New(v.Msg)
			}
			break
		case RString:
			if strings.Trim(values[0], " ") == "" {
				return errors.New(v.Msg)
			}
			break
		}
	}
	return nil
}

func ParsePageLimit(args url.Values, pagekey, pagesizekey string) (limit, offset int) {
	page := convert.Atoi(args.Get(pagekey))
	if page <= 0 {
		pageIndex := convert.Atoi(args.Get(pagekey))
		if pageIndex >= 1 {
			page = pageIndex
		} else {
			page = 1
		}
	}
	limit = convert.Atoi(args.Get(pagesizekey))
	if limit <= 0 {
		limit = 50
	}
	offset = (page - 1) * limit
	return
}

func ParseUrlData(args url.Values, urlFields, tableFields []string) ([]string, []interface{}) {
	var (
		filedKeys  []string
		filedValue []interface{}
	)
	for index, filed := range urlFields {
		value := args.Get(filed)
		if value != "" && value != "-1" {
			filedKeys = append(filedKeys, tableFields[index])
			filedValue = append(filedValue, value)
		}
	}
	return filedKeys, filedValue
}
